<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="mb-[10px]" v-show="pd.showSearch">
        <el-card shadow="hover">
          <el-form :model="pd.queryParams" ref="queryFormRef" :inline="true" label-width="68px">
            <el-form-item label="树节点名" prop="name">
              <el-input v-model="pd.queryParams.name" placeholder="请输入树节点名" clearable style="width: 240px" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="hover">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd()" v-hasPermi="['wms:warehouse:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="info" plain icon="Sort" @click="handleToggleExpandAll">展开/折叠</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="pd.showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>
      <el-table
        v-loading="pd.loading"
        :data="pd.warehouseList"
        row-key="id"
        :default-expand-all="pd.isExpandAll"
        :warehouse-props="{children: 'children', hasChildren: 'hasChildren'}"
        ref="warehouseTableRef"
      >
        <el-table-column label="父id" align="center" prop="parentId" />
        <el-table-column label="id" align="center" prop="id" />
        <el-table-column label="操作" align="center" class-name="small-padding">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['wms:order:edit']"> 修改 </el-button>
          <el-button link type="primary" icon="Plus" @click="handleAdd(scope.row)"
                     v-hasPermi="['wms:order:add']"> 新增 </el-button>
          <el-button link type="primary" icon="Plus" @click="wwpEdit(scope.row)"
                     v-if="scope.row.parentId == '0' && scope.row.children != null"
                     v-hasPermi="['wms:order:add']">产品关联</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row.id)"
                     v-hasPermi="['wms:order:remove']">删除 </el-button>
        </template>
      </el-table-column>
        <el-table-column label="名称" align="center" prop="name" />
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="sys_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="负责人" align="center" prop="userName" />
        <el-table-column label="位置" align="center" prop="location" />
        <el-table-column label="面积" align="center" prop="acreage" />
        <el-table-column label="归属部门" align="center" prop="deptName" />
        <el-table-column label="备注" align="center" prop="remark" />


      </el-table>
    </el-card>
    <!-- 添加或修改测试树对话框 -->
    <el-dialog :title="pd.dialog.title" v-model="pd.dialog.visible" width="650px" append-to-body>
      <el-form ref="warehouseFormRef" :model="pd.form" :rules="pd.rules" label-width="80px">
        <el-row>
          <el-col :span="11">
            <el-form-item label="父id" prop="parentId">
              <el-tree-select
                v-model="pd.form.parentId"
                :data="pd.warehouseOptions"
                :props="{ value: 'id', label: 'name', children: 'children' }"
                value-key="id"
                placeholder="请选择父id"
                check-strictly
              />
            </el-form-item>
            <el-form-item label="名称" prop="name">
              <el-input v-model="pd.form.name" placeholder="请输入名称" />
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="pd.form.status">
                <el-radio v-for="dict in sys_status" :key="dict.value" :label="dict.value">{{dict.name}}</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="归属部门" prop="deptId">
              <el-tree-select
                v-model="pd.form.createDept"
                :data="deptOptions"
                :props="{ value: 'id', label: 'label', children: 'children' }"
                value-key="id"
                placeholder="请选择归属部门"
                check-strictly
              />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="负责人" prop="userId">
              <UserSearch :dataText="pd.form.userName" :params="{isSupplier:true}" @ok="searchSupplier($event)" />
            </el-form-item>
            <el-form-item label="面积" prop="acreage">
              <el-input v-model="pd.form.acreage" placeholder="请输入面积" />
            </el-form-item>
            <el-form-item label="位置" prop="location">
              <el-input v-model="pd.form.location" placeholder="请输入位置" />
            </el-form-item>
            <el-form-item label="备注" prop="remark">
              <el-input v-model="pd.form.remark" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="pd.buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 库存预警 -->
    <el-dialog :title="pd.wwp.wwpDialog.title" v-model="pd.wwp.wwpDialog.visible" width="1000" append-to-body>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button icon="Plus" type="success" @click="submitWWP">保存单据</el-button>
        </el-col>
        <el-col :span="1.5">
          <ProductSearch :searchType="2" :params="{isStock:true}" @ok="lineAdd" title="产品查询" dataText="新增一行" />
        </el-col>
        <el-col :span="1.5">
          <el-button icon="Close" type="info" @click="pd.wwp.wwpDialog.visible = false">关闭</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button icon="Refresh" @click="getWWPLineList">刷新</el-button>
        </el-col>
      </el-row>
      <el-table v-loading="pd.loading" :data="pd.wwp.wwpLine">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="物品名称" align="center" prop="productName" />
        <el-table-column label="最低库存" align="center" prop="minStock">
          <template #default="scope">
            <el-input v-model.number="scope.row.minStock" placeholder="请输入最低库存" onkeyup="value=value.replace(/[^\d]/g,'')" />
          </template>
        </el-table-column>
        <el-table-column label="最高库存" align="center" prop="maxStock">
          <template #default="scope">
            <el-input v-model.number="scope.row.maxStock" placeholder="请输入最高库存" onkeyup="value=value.replace(/[^\d]/g,'')" />
          </template>
        </el-table-column>
        <el-table-column label="存储区域" align="center" prop="areaId">
          <template #default="scope">
            <el-select v-model="scope.row.areaId">
              <el-option v-for="item in pd.wwp.warehouseArea" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" icon="Delete" @click="delLine(scope.row)" v-hasPermi="['wms:warehouseProduct:del']">删除 </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="pd.wwp.lineTotal>0"
        :total="pd.wwp.lineTotal"
        v-model:page="pd.wwp.queryLineParams.pageNum"
        v-model:limit="pd.wwp.queryLineParams.pageSize"
        @pagination="getWWPLineList"
      />
    </el-dialog>
  </div>
</template>

<script setup name="Warehouse" lang="ts">
import {
  WarehouseVO,
  listWarehouse,
  getWarehouse,
  delWarehouse,
  addWarehouse,
  updateWarehouse,
  wwpVo, getWWPList, delWWP, addWWP
} from "@/views/wms/warehouse/api";
import { DeptVO } from "@/api/system/dept/types";
import api from "@/api/system/user";
import UserSearch from "@/views/system/user/search.vue";
import {UserVO} from "@/api/system/user/types";
import ProductSearch from "@/views/wms/product/search.vue";
import {ProductVO} from "@/views/wms/product/api";

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_status } = toRefs<any>(proxy?.useDict('sys_status'));
const queryFormRef = ref<ElFormInstance>();
const warehouseFormRef = ref<ElFormInstance>();
const warehouseTableRef = ref<ElTableInstance>()
const deptOptions = ref<DeptVO[]>([]);

const pd = reactive({
  warehouseList: <WarehouseVO[]>([]),
  warehouseOptions: <WarehouseVO[]>([]),
  buttonLoading: false,
  showSearch: true,
  isExpandAll: true,
  loading: false,
  form: <WarehouseVO>{},
  queryParams: <WarehouseVO>{
    parentId: undefined,
    name: undefined
  },
  rules: <ElFormRules>{
    id: [      { required: true, message: "主键不能为空", trigger: "blur" }    ],
    parentId: [      { required: true, message: "父id不能为空", trigger: "blur" }    ],
    name: [      { required: true, message: "值不能为空", trigger: "blur" }    ],
  },
  dialog: <DialogOption>{
    visible: false,
    title: ''
  },
  wwp: {
    wwpId: 0,
    wwpLine: <wwpVo[]>([]),
    wwpLineForm: <wwpVo[]>([]),
    wwpDialog: <DialogOption>{
      visible: false,
      title: '产品预警设置'
    },
    lineTotal: 0,
    queryLineParams: <wwpVo>{
      pageNum: 1,
      pageSize: 10,
    },
    areaQueryParams:<WarehouseVO>{},
    warehouseArea:<WarehouseVO[]>([])
  },
});

/** 查询测试树列表 */
async function getList() {
  pd.loading = true;
  const res = await listWarehouse(pd.queryParams);
  const data = proxy?.handleTree<WarehouseVO>(res.data, "id", "parentId");
  if (data) {
    pd.warehouseList = data;
    pd.loading = false;
  }
}

async function getAreaList(id: number) {
  pd.loading = true;
  pd.wwp.areaQueryParams.parentId = id;
  const res = await listWarehouse(pd.wwp.areaQueryParams);
  pd.wwp.warehouseArea = res.data;
  pd.loading = false;
}

/** 查询测试树下拉树结构 */
async function getWarehouseSelect() {
  pd.warehouseOptions = [];
  const data: WarehouseVO = { id: 0, parentId: 0, name: '仓库节点', children: [] };
  data.children = pd.warehouseList;
  pd.warehouseOptions.push(data);
}

// 取消按钮
function cancel() {
  reset();
  pd.dialog.visible = false;
}

// 表单重置
function reset() {
  pd.form = {}
  warehouseFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
function handleQuery() {
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 新增按钮操作 */
async function handleAdd(row?: WarehouseVO) {
  reset();
  await getWarehouseSelect();
  if (row && row.id) {
    pd.form.parentId = row.id;
  } else {
    pd.form.parentId = 0;
  }
  pd.dialog.visible = true;
  pd.dialog.title = "添加测试树";
}

/** 展开/折叠操作 */
function handleToggleExpandAll() {
  pd.isExpandAll = !pd.isExpandAll;
  toggleExpandAll(pd.warehouseList, pd.isExpandAll)
}

/** 展开/折叠操作 */
function toggleExpandAll(data: WarehouseVO[], status: boolean) {
  data.forEach((item) => {
    warehouseTableRef.value?.toggleRowExpansion(item, status)
    if (item.children && item.children.length > 0) toggleExpandAll(item.children, status)
  })
}

/** 修改按钮操作 */
async function handleUpdate(row: WarehouseVO) {
  reset();
  await getWarehouseSelect();
  if (row) {
    pd.form.parentId = row.id;
  }
  const res = await getWarehouse(row.id!);
  Object.assign(pd.form, res.data);
  pd.dialog.visible = true;
  pd.dialog.title = "修改测试树";
}

/** 提交按钮 */
function submitForm() {
  warehouseFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      pd.buttonLoading = true;
      if (pd.form.id) {
        await updateWarehouse(pd.form).finally(() => pd.buttonLoading = false);
      } else {
        await addWarehouse(pd.form).finally(() => pd.buttonLoading = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      pd.dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
async function handleDelete(row: WarehouseVO) {
  await proxy?.$modal.confirm('是否确认删除测试树编号为"' + row.id + '"的数据项？');
  pd.loading = true;
  await delWarehouse(row.id!).finally(() => pd.loading = false);
  await getList();
  proxy?.$modal.msgSuccess("删除成功");
}

/** 查询部门下拉树结构 */
const getTreeSelect = async () => {
  const res = await api.deptTreeSelect();
  deptOptions.value = res.data;
};

function searchSupplier(pVo: UserVO[]) {
  pVo.forEach((v, i, a) => {
    pd.form.userId = v.userId;
    pd.form.userName = v.nickName;
    return;
  });
}

function wwpEdit(row: any){
  pd.wwp.wwpId = row.id;
  getAreaList(row.id);
  pd.wwp.wwpLine = [];
  pd.wwp.wwpDialog.title = '产品关联设置';
  pd.wwp.wwpDialog.visible = true;
  pd.wwp.wwpDialog.title = row.name + '：' + pd.wwp.wwpDialog.title;
  getWWPLineList();
}

/** 提交按钮 */
async function submitWWP() {
  pd.buttonLoading = true;
  let error = false;
  pd.wwp.wwpLine.forEach(item => {
    if (item.minStock != null && item.maxStock != null && item.areaId != null){
      if (item.minStock >= item.maxStock || item.minStock < 0
        || item.maxStock <=0 || item.minStock > 99999999 || item.maxStock > 99999999){
        proxy?.$modal.msgWarning("产品 " + item.productName+" 库存预警数值有误，请核对后重试");
        error = true;
        return
      }
    }else {
      proxy?.$modal.msgWarning("产品 " + item.productName+" 库存预警信息未填写完整，请核对后重试");
      error = true;
      return
    }
  })
  if (error){
    return;
  }
  await addWWP(pd.wwp.wwpLine).then((res: any) => {
    pd.buttonLoading = false
    proxy?.$modal.msgSuccess(res.msg);
  })
  pd.wwp.wwpDialog.visible = false;
  await getWWPLineList();
}

/** 新增一行产品预警信息 */
async function lineAdd(vo: ProductVO[]) {
  let line: wwpVo = {};
  vo.forEach((v, i, a) => {
    line.productId = v.id as number;
    line.productName = v.name;
    line.whId = pd.wwp.wwpId;
    const findObj = pd.wwp.wwpLine.find(item => {
      if (item.productId == line.productId)return item;
    })
    if (!findObj){
      pd.wwp.wwpLineForm.push(line);
      pd.wwp.wwpLine.push(line);
    }
  });
}

/** 查询仓库产品预警信息 */
async function getWWPLineList() {
  pd.loading = true;
  pd.wwp.queryLineParams.whId = pd.wwp.wwpId;
  await getWWPList(pd.wwp.queryLineParams).then(res => {
    pd.wwp.wwpLine = res.rows;
    pd.wwp.lineTotal = res.total;
    pd.loading = false;
  });
}

/** 删除仓库产品预警信息 */
async function delLine(row: wwpVo) {
  if (pd.wwp.wwpLineForm.includes(row)) {
    const index = pd.wwp.wwpLine!.indexOf(row);
    pd.wwp.wwpLine!.splice(index, 1);
    return;
  }
  proxy?.$modal.confirm('是否确认删除 产品:"' + row.productName + '"的预警信息？').then(function () {
    const bo: wwpVo = {};
    bo.whId = row.whId;
    bo.productId = row.productId;
    return delWWP(bo);
  }).then(() => {
    const index = pd.wwp.wwpLine!.indexOf(row);
    pd.wwp.wwpLine!.splice(index, 1);
    proxy.$modal.msgSuccess("删除成功");
  });
}

onMounted(() => {
  getList();
  getTreeSelect(); // 初始化部门数据
});
</script>
